import { login, userInfo, userProfile } from '@/api/user'
import { getToken, setToken, setStartToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  // 设置token的方法
  setToken(state, token) {
    // 将token 保存至本地
    // 虽然名字都叫setToken，但要用 commit('setToken') 来调用，所以不会冲突
    state.token = token
    setToken(token)
    setStartToken()
  },
  setUserInfo(state, payload) {
    state.userInfo = payload
  }
}

const actions = {
  async login(context, data) {
    const res = await login(data)
    context.commit('setToken', res.data)
  },
  async getUserInfo(context) {
    try {
      const res1 = await userInfo()
      const res2 = await userProfile(res1.data.userId)
      context.commit('setUserInfo', {
        ...res1.data,
        ...res2.data
      })
      return res1.data.roles.menus
    } catch (error) {
      return () => {}
    }
  },
  logout(context) {
    context.commit('setToken', '')
    context.commit('setUserInfo', {})
    context.dispatch('tagsView/delAllViews', null, { root: true })
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
